package com.cloud.school.bus.teacherhelper.modules.stuclass;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.Spanned;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.android.support.jhf.debug.DebugLog;
import com.android.support.jhf.handlerui.HandlerToastUI;
import com.android.support.jhf.network.NetworkClient;
import com.android.support.jhf.network.loopj.android.http.ResponseHandlerInterface;
import com.android.support.jhf.universalimageloader.core.ImageLoader;
import com.android.support.jhf.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.android.support.jhf.utils.DateUtils;
import com.android.support.jhf.utils.ImageUtil;
import com.cloud.school.bus.teacherhelper.R;
import com.cloud.school.bus.teacherhelper.base.activity.BaseActivity;
import com.cloud.school.bus.teacherhelper.base.dialog.CustomDatePickerDialog;
import com.cloud.school.bus.teacherhelper.base.dialog.CustomListDialog;
import com.cloud.school.bus.teacherhelper.base.dialog.CustomDatePickerDialog.DatePickerListener;
import com.cloud.school.bus.teacherhelper.base.dialog.CustomListDialog.CustomListDialogItem;
import com.cloud.school.bus.teacherhelper.base.uploadpic.UploadPic;
import com.cloud.school.bus.teacherhelper.base.uploadpic.UploadPic.OnGetPicSucceed;
import com.cloud.school.bus.teacherhelper.base.utils.PictureUtil;
import com.cloud.school.bus.teacherhelper.base.view.TitleNavBarView;
import com.cloud.school.bus.teacherhelper.protocol.classmanage.AddStudentRequest;
import com.cloud.school.bus.teacherhelper.protocol.classmanage.AddStudentResponse;

/**
 * 增加学生填写详细信息
 * 
 * @author jiahongfei
 * 
 */
public class AddStudentDetailInfoActivity extends BaseActivity {

	private ImageView mHeadImageView;
	private EditText mNameEditText;
	private EditText mParentPhoneEditText;
	private TextView mGenderTextView;
	private TextView mRelationshipStudentTextView;
	private TextView mBirthdayTextView;

	private String mRelationshipString = "妈妈";
	private String mGenderString = "1";
	private String mBirthdayString;
	private String mPicBase64String;
	private String mFextString;
	private String mPicPathString;
	private int mRequestCode;

	private UploadPic mUploadPic;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_student_detail_info);
		init();
	}

	@Override
	protected void init() {

		String nameString = getIntent().getStringExtra("name");
		String parentPhoneString = getIntent().getStringExtra("parentPhone");

		mRelationshipString = getString(R.string.mother);
		mGenderString = "1";
		mBirthdayString = "2012-01-01";

		mUploadPic = new UploadPic(this);

		mBirthdayTextView = (TextView) findViewById(R.id.birthdayTextView);
		mBirthdayTextView.setText(mBirthdayString);
		mGenderTextView = (TextView) findViewById(R.id.sexTextView);
		if ("1".equals(mGenderString)) {
			mGenderTextView.setText(getString(R.string.prince));
		} else if ("2".equals(mGenderString)) {
			mGenderTextView.setText(getString(R.string.princess));
		}
		mRelationshipStudentTextView = (TextView) findViewById(R.id.relationshipStudentTextView);
		mRelationshipStudentTextView.setText(mRelationshipString);
		mHeadImageView = (ImageView) findViewById(R.id.headImageView);
		mNameEditText = (EditText) findViewById(R.id.nameEditText);
		mNameEditText.setText(nameString);
		mParentPhoneEditText = (EditText) findViewById(R.id.parentPhoneEditText);
		mParentPhoneEditText.setText(parentPhoneString);

		setListener();
		setTitleNavBar();
	}

	@Override
	protected void setListener() {
		mNameEditText.setFilters(new InputFilter[] { new InputFilter() {

			@Override
			public CharSequence filter(CharSequence source, int start, int end,
					Spanned dest, int dstart, int dend) {

				if (source.equals("\n")) {
					return "";
				}
				return source;
			}

		} });
		mParentPhoneEditText.setFilters(new InputFilter[] { new InputFilter() {

			@Override
			public CharSequence filter(CharSequence source, int start, int end,
					Spanned dest, int dstart, int dend) {

				if (source.equals("\n")) {
					return "";
				}
				return source;
			}

		} });
		mHeadImageView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mUploadPic.doPickPhotoAction();
			}
		});

		mUploadPic.setOnGetPicSucceed(new OnGetPicSucceed() {

			@Override
			public void onGetPicSucceed(String picPathString, int requestCode) {
				mPicPathString = picPathString;
				mRequestCode = requestCode;
				setHeadImageView(picPathString);
			}
		});

		Button nextButton = (Button) findViewById(R.id.nextButton);
		nextButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				addStudent();
			}
		});
		ViewGroup relationshipStudentLayout = (ViewGroup) findViewById(R.id.relationshipStudentLayout);
		relationshipStudentLayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				relationshipDialog();
			}
		});
		ViewGroup sexLayout = (ViewGroup) findViewById(R.id.sexLayout);
		sexLayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showGenderDialog();
			}
		});
		ViewGroup birthdayLayout = (ViewGroup) findViewById(R.id.birthdayLayout);
		birthdayLayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showBirthdayDialog();
			}
		});
	}

	private void showBirthdayDialog() {
		CustomDatePickerDialog customDatePickerDialog = new CustomDatePickerDialog(
				mContext, com.android.support.jhf.R.style.DialogFromDownToUp);

		try {
			String[] strings = mBirthdayTextView.getText().toString()
					.split("-");
			int year = Integer.parseInt(strings[0]);
			int monthOfYear = Integer.parseInt(strings[1]) - 1;
			int dayOfMonth = Integer.parseInt(strings[2]);
			customDatePickerDialog.init(year, monthOfYear, dayOfMonth, null);
		} catch (Exception e) {
		}

		customDatePickerDialog.setOkButton(getString(R.string.confirm), 0,
				new DatePickerListener() {

					@Override
					public void onClick(View view, int year, int monthOfYear,
							int dayOfMonth) {
						int tempMonth = monthOfYear + 1;
						int tempDay = dayOfMonth;
						String tempMonthString = tempMonth + "";
						String tempDayString = tempDay + "";
						if (tempMonth < 10) {
							tempMonthString = "0" + tempMonthString;
						}
						if (tempDay < 10) {
							tempDayString = "0" + tempDayString;
						}
						final String tempString = year + "-"
								+ (tempMonthString) + "-" + tempDayString;
						// 当前时间
						Calendar curCalendar = Calendar.getInstance();
						curCalendar.setTimeInMillis(DateUtils.getDateMillis(
								DateUtils.getCurrentDate("yyyy-MM-dd"),
								"yyyy-MM-dd"));
						// 选择的时间
						Calendar selCalendar = Calendar.getInstance();
						selCalendar.setTimeInMillis(DateUtils.getDateMillis(
								tempString, "yyyy-MM-dd"));
						// 选择的时间一定要小于当前时间
						if (selCalendar.compareTo(curCalendar) <= 0) {
							mBirthdayTextView.setText(tempString);
							mBirthdayString = tempString;
						} else {
							HandlerToastUI
									.getHandlerToastUI(
											mContext,
											getString(R.string.please_set_the_correct_birthday));
						}
					}
				});
		customDatePickerDialog.setCancelButton(getString(R.string.cancel), 0,
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {

					}
				});
		customDatePickerDialog.show();
	}

	private void relationshipDialog() {
		CustomListDialog customListDialog = CustomListDialog
				.getCustomListDialog(mContext,
						com.android.support.jhf.R.style.DialogFromDownToUp);
		final List<CustomListDialogItem> customListDialogItems = new ArrayList<CustomListDialog.CustomListDialogItem>();
		CustomListDialogItem customListDialogItem1 = new CustomListDialogItem();
		customListDialogItem1.text = getString(R.string.father);
		customListDialogItem1.textColor = getResources().getColor(
				R.color.btn_bg_blue);
		customListDialogItem1.textSize = 18;
		customListDialogItems.add(customListDialogItem1);
		CustomListDialogItem customListDialogItem2 = new CustomListDialogItem();
		customListDialogItem2.text = getString(R.string.mother);
		customListDialogItem2.textColor = getResources().getColor(
				R.color.btn_bg_blue);
		customListDialogItem2.textSize = 18;
		customListDialogItems.add(customListDialogItem2);

		CustomListDialogItem customListDialogItem3 = new CustomListDialogItem();
		customListDialogItem3.text = getString(R.string.grandpa);
		customListDialogItem3.textColor = getResources().getColor(
				R.color.btn_bg_blue);
		customListDialogItem3.textSize = 18;
		customListDialogItems.add(customListDialogItem3);

		CustomListDialogItem customListDialogItem4 = new CustomListDialogItem();
		customListDialogItem4.text = getString(R.string.grandma);
		customListDialogItem4.textColor = getResources().getColor(
				R.color.btn_bg_blue);
		customListDialogItem4.textSize = 18;
		customListDialogItems.add(customListDialogItem4);

		CustomListDialogItem customListDialogItem5 = new CustomListDialogItem();
		customListDialogItem5.text = getString(R.string.other);
		customListDialogItem5.textColor = getResources().getColor(
				R.color.btn_bg_blue);
		customListDialogItem5.textSize = 18;
		customListDialogItems.add(customListDialogItem5);

		customListDialog.setMessage(customListDialogItems);
		customListDialog.setTitle(getString(R.string.relationship));
		customListDialog.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				CustomListDialogItem customListDialogItem = customListDialogItems
						.get(arg2);
				mRelationshipString = customListDialogItem.text;
				mRelationshipStudentTextView.setText(customListDialogItem.text);
			}
		});
		customListDialog.show();
	}

	private void showGenderDialog() {
		CustomListDialog customListDialog = CustomListDialog
				.getCustomListDialog(mContext,
						com.android.support.jhf.R.style.DialogFromDownToUp);
		List<CustomListDialogItem> customListDialogItems = new ArrayList<CustomListDialog.CustomListDialogItem>();
		CustomListDialogItem customListDialogItem1 = new CustomListDialogItem();
		customListDialogItem1.text = getString(R.string.prince);
		customListDialogItem1.textColor = getResources().getColor(
				R.color.btn_bg_blue);
		customListDialogItem1.textSize = 18;
		customListDialogItems.add(customListDialogItem1);
		CustomListDialogItem customListDialogItem2 = new CustomListDialogItem();
		customListDialogItem2.text = getString(R.string.princess);
		customListDialogItem2.textColor = getResources().getColor(
				R.color.btn_bg_blue);
		customListDialogItem2.textSize = 18;
		customListDialogItems.add(customListDialogItem2);
		customListDialog.setMessage(customListDialogItems);
		customListDialog.setTitle(getString(R.string.gender));
		customListDialog.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (0 == arg2) {
					// 男孩
					mGenderTextView.setText(getString(R.string.prince));
				} else if (1 == arg2) {
					// 女孩
					mGenderTextView.setText(getString(R.string.princess));
				}
				mGenderString = (arg2 + 1) + "";
			}
		});
		customListDialog.show();
	}

	@Override
	protected void setTitleNavBar() {
		TitleNavBarView titleNavBarView = (TitleNavBarView) findViewById(R.id.titleNavBarView);
		titleNavBarView.setMessage(getString(R.string.add_student));
		titleNavBarView.setLeftButtonOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// finish();
				cancel();
			}
		});
		titleNavBarView.setRightButtonVisibility(View.INVISIBLE);
	}

	private void setHeadImageView(String picPathString) {
		String datePicString = PictureUtil.getPicString(picPathString, 512);
		if (null != datePicString) {
			mPicBase64String = datePicString;
			mFextString = picPathString.substring(picPathString
					.lastIndexOf(".") + 1);
		}
		ImageLoader.getInstance().displayImage(
				Uri.decode(Uri.fromFile(new File(picPathString)).toString()),
				mHeadImageView, mApplication.mNoCacheDisplayImageOptions,
				new SimpleImageLoadingListener() {
					@Override
					public void onLoadingComplete(String imageUri, View view,
							Bitmap loadedImage) {
						// mHeadImageView.setImageBitmap(loadedImage);
						if (imageUri.startsWith("http://")) {
							mHeadImageView.setImageBitmap(loadedImage);
						} else if (imageUri.startsWith("file:///")) {
							ImageUtil.setRotaingImageBitmap(
									imageUri.replace("file:///", "/"),
									loadedImage, mHeadImageView);
						} else {
							ImageUtil.setRotaingImageBitmap(imageUri,
									loadedImage, mHeadImageView);
						}
					}
				});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (null != mUploadPic) {
			mUploadPic.onActivityResult(requestCode, resultCode, data);
		}
		switch (requestCode) {
		case 0: {
			// 关联家长手机号界面返回
			switch (resultCode) {
			case RESULT_OK: {
				setResult(RESULT_OK);
				// finish();
				cancel();
				break;
			}
			case RESULT_CANCELED: {
				break;
			}
			default:
				break;
			}
			break;
		}
		default:
			break;
		}
	}

	private void addStudent() {
		NetworkClient.getNetworkClient().PostRequest(
				new AddStudentRequest(mContext, mRelationshipString,
						mNameEditText.getText().toString(),
						mParentPhoneEditText.getText().toString(),
						mGenderString, mBirthdayString, mPicBase64String),
				new AddStudentResponse() {
					@Override
					public void onResponse(
							ResponseHandlerInterface responseHandlerInterface) {
						if ("1".equals(code)) {
							if ("1".equals(student.key)) {
								// 1 为手机号存在关联学生
								Intent intent = new Intent(mContext,
										AddStudentRelevanceParentActivity.class);
								intent.putExtra("name", mNameEditText.getText()
										.toString());
								intent.putExtra("parentPhone",
										mParentPhoneEditText.getText()
												.toString());
								intent.putExtra("sex", mGenderString);
								intent.putExtra("birthday", mBirthdayString);
								intent.putExtra("picbase64", mPicBase64String);
								intent.putExtra("fext", mFextString);
								intent.putExtra("Student", student);
								startActivityForResult(intent, 0);
							} else if ("2".equals(student.key)) {
								// 2为不存在关联学生
								mApplication.mStudentList.add(student);
								setResult(RESULT_OK);
								// finish();
								cancel();
								HandlerToastUI.getHandlerToastUI(mContext,
										getString(R.string.add_successfully));
							}

							DebugLog.logI(student.toString());
						} else if ("-3".equals(code)) {
							HandlerToastUI.getHandlerToastUI(mContext,
									"该学生已存在机构中");
						} else if ("-4".equals(code)) {
							HandlerToastUI
									.getHandlerToastUI(mContext, "不是老师操纵");
						} else if ("-2".equals(code)) {
							HandlerToastUI.getHandlerToastUI(mContext,
									"性别或生日姓名不能为空");
						}
					}
				});
	}

	private void cancel() {
		if (UploadPic.PHOTO_PICKED_WITH_DATA == mRequestCode) {
			mUploadPic.removePicture(mPicPathString);
		}
		finish();
	}

}
